package com.lanlang.logindemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lanlang.logindemo.entity.LoginResponse;
import com.lanlang.logindemo.interceptor.CommonInterceptor;
import com.lanlang.logindemo.utils.Utils;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Call;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {
    private TextView txtUser, txtPwd;
    private Button btnLogin, btnReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        初始化页面
        initView();
        initListener();
    }

    private void initView() {
//        找到元素
        txtUser = findViewById(R.id.txt_user);
        txtPwd = findViewById(R.id.txt_pwd);
        btnLogin = findViewById(R.id.btn_login);
        btnReset = findViewById(R.id.btn_reset);
    }

    private void initListener() {
//        添加时间监听
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginForm();
            }
        });
//        输入框置空
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtUser.setText("");
                txtPwd.setText("");
            }
        });
    }

//    登录操作
    private void loginForm() {
        String username = String.valueOf(txtUser.getText());
//        String password = String.valueOf(txtPwd.getText());

//        加密处理
        String password = Utils.encodeMD5(String.valueOf(txtPwd.getText()));

        Toast t = Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT);
        new Thread() {
            @Override
            public void run() {
                // 使用拦截器
                CommonInterceptor commonInterceptor = new CommonInterceptor();
//                OkHttpClient client = new OkHttpClient.Builder().addInterceptor(commonInterceptor).build();
                // 直接new一个新的拦截器
                OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
                    @NonNull
                    @Override
                    public Response intercept(@NonNull Chain chain) throws IOException {
                        // 获取当前时间戳
                        String ts = String.valueOf(System.currentTimeMillis()/1000);
                        String sign = Utils.encodeMD5(ts);
                        Request request = chain.request().newBuilder().addHeader("ts", ts).addHeader("sign", sign).build();
                        // 继续执行后面的逻辑
                        Response response = chain.proceed(request);

                        return response;
                    }
                }).build();
                FormBody form = new FormBody.Builder().add("user", username).add("pwd", password).build();
                String url = "http://192.168.1.111:8084/login";

                // 数据序列化
                LoginResponse okResponse = new LoginResponse(0, "登录成功");
                String loginSuccessStr = new Gson().toJson(okResponse);
                System.out.println("登录成功:"+loginSuccessStr);
                // 发起请求
                Request req = new Request.Builder().url(url).post(form).build();
                Call call = client.newCall(req);
                try {
                    Response res = call.execute();
                    ResponseBody body = res.body();
                    String dataString = body.string();
                    // 反序列化
                    LoginResponse obj = new Gson().fromJson(dataString, LoginResponse.class);
                    if (obj.code == 0) {

                        // 将token持久化
                        SharedPreferences sp = getSharedPreferences("login_token",MODE_PRIVATE);
                        // 获取token
//                        String token = sp.getString("token", "");

                        SharedPreferences.Editor editor = sp.edit();
                        // 修改key
                        editor.putString("token", obj.token);
                        // 删除key
//                        editor.remove("token");

                        editor.apply();

                        Log.e("请求发送成功:", dataString);
                        t.show();
                        // 跳转到首页
                        Intent intent = new Intent(MainActivity.this, IndexActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    Log.e("Main:", e.toString());
                }
            }
        }.start();
    }
}